#!/bin/bash
#
# update-theme:
#    subversion export of our theme's repo for reclaimyourdna
#    based on staging.org's full-update
#
# (c) 2009 AMLN McGreggor. Some rights reserved.
#     This work is licenced under a Creative Commons Licence:
#       <http://creativecommons.org/licenses/by-nc-sa/2.0/uk/>
#
#  Email: <adam@amyl.org.uk>; WWW: http://blog.amyl.org.uk
#
# $Id:$ 
#

set -e
# set -x 	# <-- debug mode

# variables (in the order they appear, below):
MAINDIR=/data/vhosts/reclaimyourdna.com
LOCKFILE=${MAINDIR}/lock
WORKDIR=${MAINDIR}/deploy
SVNREPO=http://reclaimyourdna.googlecode.com/svn/trunk
BRANCH=themes
WPPATH=docs/wp-content/${BRANCH}
PROJECT=reclaimyourdna
STAMPFILE=$MAINDIR/docs/datestamp.txt

umask=002	# group write

# so, we don't run this as root, quick check
id=$( ls -lnd /proc/$$ | awk '{print $3}' )
if [ $id = 0 ]; then
	echo 'This should not be run as root'
	exit 1
fi

# perhaps check if we're a member of the 
# staging (deploy) group here, at a later date

# lockfiles. v. important.
if [ -e ${LOCKFILE} ]; then
	echo 'Update already in progress; please try again later'
	exit 2
fi

touch ${LOCKFILE}
if [ ! -e ${LOCKFILE} ]; then
	echo 'Failed to create lockfile'
	exit 3
fi

if [ ! -d ${WORKDIR} ]; then
	mkdir -p ${WORKDIR}
fi
cd ${WORKDIR}

TMPDIR=`mktemp -d -p ${WORKDIR} svn-export.XXXXX` || exit 
cd ${TMPDIR}

# and now, subversion's bitch
echo 'Now doing the subversion export. wheeeee'
echo 'this may take a few mins'
svn export -q --force ${SVNREPO}/${BRANCH}

cd ${WORKDIR}

# This is not atomic -- there is an instant in which the live site
# breaks.
if [ -d ${MAINDIR}/${BRANCH}.old ] ; then
    rm -rf ${MAINDIR}/${BRANCH}.old; 
fi

mv ${MAINDIR}/${BRANCH} ${MAINDIR}/${BRANCH}.old	# rename existing directory, that is
mv ${TMPDIR} ${MAINDIR}/${BRANCH}

# this creates an 'extra' $BRANCH dir, so, erm,...
mv ${MAINDIR}/${BRANCH}/${BRANCH} ${MAINDIR}/${BRANCH}-foo || exit 1
rm -rf ${MAINDIR}/${BRANCH}
mv ${MAINDIR}/${BRANCH}-foo ${MAINDIR}/${BRANCH}

# fix-up perms, please -- just in case.
chgrp -R reclaimdna ${MAINDIR}/${BRANCH}
find ${MAINDIR}/${BRANCH}/ -type d -exec chmod 2775 {} \;
find ${MAINDIR}/${BRANCH}/ -type f -exec chmod 0664 {} \;

# now for the live site...
# firstly check the dirs we want to replace aren't directories

# activate the theme, damnit!
if [ -d ${MAINDIR}/${WPPATH}/${PROJECT} ]; then
    mv ${MAINDIR}/${WPPATH}/${PROJECT} ${MAINDIR}/${PROJECT}.`date '+%Y%m%d'`
    ln -s ${MAINDIR}/${BRANCH}/${PROJECT} ${MAINDIR}/${WPPATH}/${PROJECT}
else
    if [ -L ${MAINDIR}/{WPPATH}/${PROJECT} ]; then
        rm -f ${MAINDIR}/${WPPATH}/${PROJECT}
        ln -s ${MAINDIR}/${BRANCH}/${PROJECT} ${MAINDIR}/${WPPATH}/${PROJECT}
    fi
fi

# Ok, so that went well, now we can do a wee bit of logging
( echo $USER'@'$HOSTNAME 'performed an update on:' `date` ) > ${STAMPFILE}

# and remove the lockfile
rm -f $LOCKFILE

# and mail
mail -s 'Deployed Theme: reclaimyourdna' reclaimyourdna-dev@googlegroups.com < ${STAMPFILE}
